package com.test.Servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class upLoadFile extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
//			PropertyConfigurator.configure(req.getRealPath("/")+"WEB-INF\\log4j.properties");
			Logger logger = Logger.getLogger(upLoadFile.class.getName());
			logger.info("start................................");
//			logger.error("strat...........");
			System.out.println("..............");
			String realPath = req.getRealPath("/");
			String tempPath = realPath + "\\fileUpload\\tmp"; // 用于存放临时文件的目录
			String realUpLoadFilePath = realPath + "\\fileUpload";
			File tempPathFile = new File(tempPath);
			File realUpLoadFile = new File(realUpLoadFilePath);

			if (!tempPathFile.isDirectory()) {
				tempPathFile.mkdirs();
			}
			if (!realUpLoadFile.isDirectory()) {
				realUpLoadFile.mkdirs();
			}
			// 创建DiskFileUpload
			DiskFileUpload fu = createDiskUpload(tempPath);
			// 得到所有的文件
			List<?> fileItems = fu.parseRequest(req);
			Iterator<?> i = fileItems.iterator();
			// 依次处理每一个文件：
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (!fi.isFormField()) {
					// 获得文件名，这个文件名包括路径：
					String fileName = fi.getName();
					if (fileName != null) {
						// 在这里可以记录用户和文件信息
						fi.write(new File(realUpLoadFilePath + File.separator
								+ fileName));
						fi.getOutputStream().flush();
						fi.delete();// 删除临时文件
					}
				}
			}
			//跳转到下载附件列表页面
			req.getRequestDispatcher("downFileList").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
			resp.sendRedirect("error.jsp");
		}

	}

	// 创建DiskFileUpload
	private DiskFileUpload createDiskUpload(String tempPath) {
		DiskFileUpload fu = new DiskFileUpload();
		// 设置中文编码
		fu.setHeaderEncoding("UTF-8");
		// 设置最大文件尺寸大小 4M
		fu.setSizeMax(4194304L);
		// 设置缓冲区大小，这里是4kb
		fu.setSizeThreshold(4096);
		// 设置临时目录：
		fu.setRepositoryPath(tempPath);
		
		return fu;
	}

}
